package com.af.system.api.list;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : zhenyun.su
 * @comment : 供应商Api接口列表
 *   host： 供应商主机地址可以加载配置时注入进来； 格式：http://localhost:path/querypath
 * @since : 2020/6/23
 */

public abstract class AfApiList {
    protected static List<AfApi> apis = new ArrayList<>();

    /**
     * @comment : 初始化所有供应商api列表，
     *   title: 必须唯一
     *   contextPath: 不能以 / 符号开头
     *   requestParam: ?name1=%s&name2=%s； 若contextPath带了参数则用&name1=%s
     */
    static {
        add("getToken", "x3", "x3-service-archives-center/login/mobile/user/v1/%s/%s/pc/zh-cn");
        add("test", "wechat", "x3-service-retail-center/retail/ocorders/deal/pick/send/sure", "?access_token=%s");
    }

    protected static void clear() {
        apis.clear();
    }

    protected static void add(String title, String type, String contextPath) {
        add(title, type, contextPath, "");
    }

    protected static void add(String title, String type, String contextPath, String requestParam) {
        apis.add(AfApi.of(title, String.valueOf(apis.size()+1), type, contextPath, requestParam));
    }

    public static AfApi getApi(String title)  {
        for (AfApi api : apis) {
            if (title.equals(api.getTitle())) {
                return api;
            }
        }
        return null;
    }

    /*
     * @comment : 获取完整queryPath，args值个数必须和ContextPath带 %s 占位符个数一致
     */
    public static String getQueryPath(String title, Object... args) {
        return String.format(getQueryPath(title), args);
    }

    public static String getQueryPath(String title) {
        for (AfApi api : apis) {
            if (title.equals(api.getTitle())) {
                return api.getContextPath();
            }
        }
        return null;
    }

    /*
     * @comment : 获取完整的请求参数：args值个数必须和requestParam带 %s 占位符个数一致
     * ?access_token=%s
     */
    public static String getRequestParam(String title, Object... args) {
        for (AfApi api : apis) {
            if (title.equals(api.getTitle())) {
                return String.format(api.getRequestParam(), args);
            }
        }
        return null;
    }
}
